import router from '../../router'
import ByteBuffer from 'bytebuffer'
import mqtt from '../../libs/mqtt'
import grouIcon from '../../assets/img/groupIcon.png'

var Long = require("long")
import { getValue } from '@/libs/util'
import { byteToString, getCanvas, arrayBufferToBase64 } from '../../libs/util'
import default_img from '../../assets/img/Icon1@2x.png'
import {
    _pullUserRequest,
    _getFriendsResult,
    _userResult,
    _version,
    _userRequest,
    _message,
    _conversation,
    _messageContent,
    _notifyMessage,
    _pullMessageRequest,
    _connectAckPayload,
    _pullMessageResult,
    _messageRes,
    _getUploadTokenResult,
    _createGroupRequest,
    _group,
    _groupInfo,
    _groupMember,
    _pullGroupMemberRequest,
    _pullGroupMemberResult,
    _groupMemberRes,
    _AddGroupMemberRequest,
    _RemoveGroupMemberRequest,
    _pullGroupInfoResult,
    _groupInfoRes
} from '../../pbApi/pb_WFCMessage'

//获取当前时间
const now = new Date();


const state = {
    // 输入的搜索值
    searchText: '',
    // 当前登录用户handleLogin
    user: {
        name: getValue('userInfo').name,
        displayName: getValue('userInfo').displayName,
        portrait: getValue('userInfo').portrait,
        userId: getValue('userInfo').uid,
        msg_head: ''
    },
    // 对话好友列表
    chatlist: [],
    // 好友列表
    friendlist: [],
    // 群列表：
    grouplist: [],
    //emoji表情
    emojis: [
        { file: '100.gif', code: '/::)', title: '微笑', reg: /\/::\)/g }
    ],
    // 得知当前选择的是哪个对话
    selectId: 0,
    // 得知当前选择的是哪个好友
    selectFriendId: 0,
    // url 群合成图片用
    // group_url: '/upload'
    group_url: ''
}

const mutations = {
    // 创建群
    CREATING_GROUP(state, obj) {
        if (obj.list.length > 1) {
            let nameList = []
            let groupParm = {
                groupInfo: '',
                groupMember: []
            }
            groupParm.groupMember.push(_groupMember(state.user.userId))
            obj.list.map(item => {
                groupParm.groupMember.push(_groupMember(item.uid))
                nameList.push(item.displayName)
            })
            groupParm.groupInfo = _groupInfo({ name: nameList.join(', ') })
            mqtt.mqttPublish('GC', _createGroupRequest({ group: _group(groupParm) }), (data) => {
                // state.selectId = byteToString(data)
                console.log("创建群成功",byteToString(data))
            })
        } else {
            let session
                // 查询会话列表
            session = state.chatlist.find((item, i) => {
                    if (item.uid == obj.list[0].uid) {
                        let obj = state.chatlist.splice(i, 1)
                        state.chatlist.unshift(obj[0])
                    }
                    return item.uid == obj.list[0].uid
                })
                // 查通讯录
            if (!session) {
                var result = state.friendlist.find(friend => friend.uid == obj.list[0].uid)
                session = {
                    uid: obj.list[0].uid,
                    type: result.type,
                    user: {
                        name: result.displayName,
                        portrait: result.portrait
                    },
                    messages: []
                }
                state.chatlist.unshift(session)
            }
            state.selectId = obj.list[0].uid
            router.push({ path: '/chat' })
        }
    },
    // 群头像合成 GET_CANVAS
    GET_CANVAS(state, data) {
        var uid = data.uid
        let arrListUrl = data.urlList
        console.log(arrListUrl)
        var base64 = {}; //用来装合成的图片
        var c = document.createElement('canvas'); //创建一个canvas
        var ctx = c.getContext('2d'); //返回一个用于在画布上绘图的2维环境
        var len = arrListUrl.length; //获取需要组合的头像图片的张数
        // var a = 0; //初始化需要组合头像的长度
        // var b = 0; //初始化需要组合头像的宽度
        c.width = 40; //定义canvas画布的宽度
        c.height = 40; //定义canvas画布的高度
        ctx.rect(0, 0, c.width, c.height); //画矩形
        ctx.fillStyle = '#fff'; //设置矩形颜色
        ctx.fill();
        const drawing = (n) => {
            if (len == 3) {
                if (n < 3) {
                    var img = new Image()
                    img.setAttribute('crossOrigin', 'Anonymous')
                    img.src = arrListUrl[n]
                    img.onload = function() {
                        if (n == 0) {
                            ctx.drawImage(img, 10, 0, 20, 20)
                        }
                        if (n == 1) {
                            ctx.drawImage(img, 0, 20, 20, 20)
                        }
                        if (n == 2) {
                            ctx.drawImage(img, 20, 20, 20, 20)
                        }
                        drawing(n + 1)
                    }
                } else {
                    setTimeout(() => {
                        state.chatlist.map(item => {
                            if (item.uid == uid) {
                                item.user.portrait = c.toDataURL("image/jpg")
                            }
                        })
                    }, 0)
                }
            } else {
                if (n < 4) {
                    var img = new Image()
                    img.src = arrListUrl[n]
                    img.setAttribute('crossOrigin', 'Anonymous')
                    img.onload = function() {
                        if (n == 0) {
                            ctx.drawImage(img, 0, 0, 20, 20)
                        }
                        if (n == 1) {
                            ctx.drawImage(img, 20, 0, 20, 20)
                        }
                        if (n == 2) {
                            ctx.drawImage(img, 0, 20, 20, 20)
                        }
                        if (n == 3) {
                            ctx.drawImage(img, 20, 20, 20, 20)
                        }
                        drawing(n + 1)
                    }
                } else {
                    setTimeout(() => {
                        state.chatlist.map(item => {
                            if (item.uid == uid) {
                                item.user.portrait = c.toDataURL("image/jpg")
                            }
                        })
                    }, 0)
                }
            }

        }
        drawing(0)
    },
    // 拉取群信息
    GOROUP_INFO(state, data){
        let obj = data
        let _this = this
        mqtt.mqttPublish('GPGI', _pullUserRequest([_userRequest(obj.uid)]), (data) => {
            if(data.length > 0){
                let groupInfo = _groupInfoRes(_pullGroupInfoResult(data).getInfoList()[0])
                _this.commit('GROUP_CHAT',{pullMsg:obj.pullMsg,groupInfo:groupInfo}) //建立会话
            }
        })
    },
    // 群接受消息处理
    CHAT_GROUP_TYPE(state, pullMsg) {
        var _this = this
        var uid = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.target
        var type = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).content.type
        if(pullMsg.ident == 1){
            if(type == 104 || type == 108 || type == 105 || type == 106){ //已处理的消息type
                _this.commit('GOROUP_INFO', {uid:uid,pullMsg:pullMsg})
            }
        }else{
            if(type == 108){ //解散群
                _this.commit('GOROUP_INFO', {pullMsg:pullMsg,uid:uid})
            }
            else if(type == 1 || type == 110){ //判断这个群是否在会话列表
                let obj = state.chatlist.find(item=> item.uid == uid)
                if(obj)_this.commit('GOROUP_INFO', {pullMsg:pullMsg,uid:uid,session:obj})
                else{
                    _this.commit('GOROUP_INFO', {pullMsg:pullMsg,uid:uid})
                }
            }
            else{
                _this.commit('GOROUP_INFO', {pullMsg:pullMsg,uid:uid})
            }
        }
    },
    // 获取群成员
    GROUP_MEMBERS(state, parm) {
        mqtt.mqttPublish('GPGM', _pullGroupMemberRequest(parm), (data) => {
            let memberList = _pullGroupMemberResult(data)
            let list = _groupMemberRes(memberList)
            let groupList = []
            state.chatlist.map(item => {
                if (item.uid == parm.target) {
                    item.members = list
                    groupList = item
                }
            })
            this.commit('GROUP_INFO', {groupList:groupList,uid:parm.target,pullMsg:parm.pullMsg}) //获取群成员信息
        })
    },
    // 获取群成员信息
    GROUP_INFO(state, evt) {
        var list = []
        evt.groupList.members.map(item => {
            if (item.type != 4) {
                list.push(_userRequest(item.uid))
            }
        })
        mqtt.mqttPublish('UPUI', _pullUserRequest(list), (data) => {
            let userInfo = _userResult(data)
            let memberObj = {}
            let urlList = []
            let urlObj = {}
            userInfo.map((e, index) => {
                let info = state.friendlist.some(k=> {
                    e.alias = k.alias
                    return e.uid == k.uid
                })

                if (index < 4) {
                    urlList.push(e.portrait ? e.portrait : default_img)
                }

                if(info){
                    memberObj[e.uid] = e
                    return false
                }
                memberObj[e.uid] = e

               
                // if (index < 4) {
                //     urlList.push(e.portrait ? "/fs" + e.portrait.split('/fs')[1] : default_img)
                // }
                // if (index < 3) {
                //     item.user.name += index < 2 ? e.name + ", " : e.name
                // }
            })
            evt.groupList.memberListInfo = memberObj
            this.commit('GROUP_CHAT_TYPE', {pullMsg:evt.pullMsg,uid:evt.uid,session:evt.groupList})
            // 群头像合成
            // urlObj[item.uid] = urlList
            // this.commit('GET_CANVAS', { urlList: urlList, uid: evt.uid })

            setTimeout(()=>{router.push({ path: '/chat' })},0)
            
            
        })
    },
    // 连接成功拿到connack payload
    CONNECT_ACK_PAYLOAD(state, obj) {
        let data = _connectAckPayload(obj)
        state.msg_head = data.msg_head.toString()
    },
    // 好友列表
    FRIEND_LIST(state) {
        var timestamp = (new Date()).valueOf()
        state.friendlist = []
        mqtt.mqttPublish('FP', _version(0), (data) => {
            var friendList = _getFriendsResult(data)
            let list = []
            friendList.map(function(evt) {
                list.push(_userRequest(evt.uid))
            })
            mqtt.mqttPublish('UPUI', _pullUserRequest(list), (data) => {
                let userInfo = _userResult(data)
                userInfo.map(e => {
                    let info = friendList.some(k=> {
                        e.alias = k.alias
                        return e.uid == k.uid
                    })
                    if(info){
                        state.friendlist.push(e)
                    }
                })
                // 拉取历史记录消息 （会话列表）
                this.commit('get_History')
            })
        })
    },
    // 从localStorage 中获取数据
    initData(state) {
        let data = localStorage.getItem('vue-chat');
        if (data) {
            state.chatlist = JSON.parse(data);
        }
    },
    // 获取搜索值
    search(state, value) {
        state.searchText = value
    },
    // 得知用户当前选择的是哪个对话。便于匹配对应的对话框
    selectSession(state, value) {
        state.selectId = value
            // 点击好友消耗掉未读消息
        let dqText = state.chatlist.find(item => item.uid == state.selectId)
        dqText.messages.map(item => {
            item.redDot = 1
        })
    },
    // 得知用户当前选择的是哪个好友。
    selectFriend(state, value) {
        state.selectFriendId = value
    },
    // 发送图片
    UPLOAD(state) {
        mqtt.mqttPublish('GQNUT', "1", (data) => {
            console.log(_getUploadTokenResult(data))
        })
    },
    // 发送文字消息
    sendMessage(state, msg) {
        let msgparm = {
            conversation: _conversation({ type: msg.conversationType, target: state.selectId, line: 0 }),
            content: _messageContent({ type: msg.type, content: msg.content }),
            fromUser: state.user.userId
        }
        let result = state.chatlist.find((item, i) => {
            if (item.uid == state.selectId) {
                let obj = state.chatlist.splice(i, 1)
                obj[0].date = (new Date()).valueOf()
                state.chatlist.unshift(obj[0])
            }
            return item.uid == state.selectId
        })
        result.messages.push({
            type: msg.type,
            content: msg.content,
            date: (new Date()).valueOf(),
            user:{
                name:state.user.displayName,
                portrait: state.user.portrait
            },
            self: true,
            loading: 1 // 1 loading 2 失败或超时 3 成功
        })
        mqtt.mqttPublish('MS', _message(msgparm), (data,code) => {
            if(code == 0){
                var payload = ByteBuffer.wrap(data, 0, 16);
                var messageId = payload.readLong().toString()
                var timestamp = payload.readLong().toString()
                result.messages[result.messages.length - 1].loading = 3
                console.log('发送消息成功',timestamp)
            }else{
                result.messages[result.messages.length - 1].loading = 2
                console.log('发送消息失败',timestamp)
            }
        })
    },
    // 发送图片
    sendPhoto(state, msg){
        let result = state.chatlist.find((item, i) => {
            if (item.uid == state.selectId) {
                let obj = state.chatlist.splice(i, 1)
                obj[0].date = (new Date()).valueOf()
                state.chatlist.unshift(obj[0])
            }
            return item.uid == state.selectId
        })
        result.messages.push({
            type: msg.type,
            content: msg.content,
            data: arrayBufferToBase64(msg.data),  //缩略图
            remoteMediaUrl: msg.remoteMediaUrl, //原图
            date: (new Date()).valueOf(),
            user:{
                name:state.user.displayName,
                portrait: state.user.portrait
            },
            self: true,
            loading: 1 // 1 loading 2 失败或超时 3 成功
        })
        
    },
    // 发送图片上传图片成功并发送
    handlePhotoRes(state, msg){
        let msgparm = {
            conversation: _conversation({ type: msg.conversationType, target: state.selectId, line: 0 }),
            content: _messageContent({ type: msg.type, content: msg.content , mediaType:msg.mediaType, data: msg.data, remoteMediaUrl: msg.remoteMediaUrl }),
            fromUser: state.user.userId
        }
        let result = state.chatlist.find(item => state.selectId == item.uid)
        mqtt.mqttPublish('MS', _message(msgparm), (data,code) => {
            if(code == 0){
                var payload = ByteBuffer.wrap(data, 0, 16);
                var messageId = payload.readLong().toString()
                var timestamp = payload.readLong().toString()
                result.messages[result.messages.length - 1].loading = 3
                console.log('发送消息成功',timestamp)
            }else{
                result.messages[result.messages.length - 1].loading = 2
                console.log('发送消息失败',timestamp)
            }
        })
    },
    // 私聊消息处理
    PRIVATE_CHAT(state, pullMsg){
        var to_user = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.target
        var from_user = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).from_user  //发送者
        var type = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.type
        var uid = from_user == state.user.userId ? to_user : from_user
        var res = state.friendlist.find(friend => friend.uid == uid)
        var objInfo = from_user == state.user.userId ? state.user : state.friendlist.find(friend => friend.uid == uid)
        var redDot = () => {
            if(pullMsg.ident == 1){
                return 1
            }else{
                if(state.selectId == uid) return 1
                else return 0
            }
        }
        // console.log("接受者",to_user)
        // console.log("发送者",from_user)
        var session
        session = state.chatlist.find((item, i) => {
            if (item.uid == uid) {
                let ses = state.chatlist.splice(i, 1)
                ses[0].date = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).server_timestamp
                state.chatlist.unshift(ses[0])
            }
            return item.uid == uid
        })
        if (!session) {
            let result = res
            session = {
                uid: uid,
                type: type,
                date: _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).server_timestamp,
                user: {
                    name: result.alias == "" ? result.displayName : result.alias,
                    portrait: result.portrait
                },
                messages: [],
                images: []
            }
            state.chatlist.unshift(session)
        }
        pullMsg.messageList.map(item => {
            var msgContent = _messageRes(item).content.content
            var msgType = _messageRes(item).content.type
            if(msgType == 90 || msgType == 80 || msgType == 4 || msgType == 400 || msgType == 402){
                msgContent = "收到不支持的消息，请在手机上查看"
            }
            session.messages.push({
                user: {
                    name: !objInfo.alias || objInfo.alias == '' ? objInfo.displayName : objInfo.alias,
                    portrait: objInfo.portrait
                },
                type: _messageRes(item).content.type,
                content: msgContent,
                data: arrayBufferToBase64(_messageRes(item).content.data),
                remoteMediaUrl: _messageRes(item).content.remoteMediaUrl,
                date: _messageRes(item).server_timestamp,
                redDot: redDot(), //判断是否读取过   0未读取过 1读取过
                self: _messageRes(item).from_user == state.user.userId ? true : false
            })
            session.messages.sort(function(a, b) {
                var x = a.date
                var y = b.date
                return x < y ? -1 : x > y ? 1 : 0;
            })
        })
    },
    // 群聊type
    GROUP_CHAT(state, data){
        var pullMsg = data.pullMsg
        var groupInfo = data.groupInfo
        var uid = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.target
        var type = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.type
        var session
        session = state.chatlist.find((item, i) => {
            if (item.uid == uid) {
                let obj = state.chatlist.splice(i, 1)
                obj[0].date = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).server_timestamp
                state.chatlist.unshift(obj[0])
            }
            return item.uid == uid
        })
        if (!session) {
            session = {
                uid: uid,
                type: type,
                date: _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).server_timestamp,
                user: {
                    name: groupInfo.name,
                    portrait: groupInfo.portrait ? groupInfo.portrait : grouIcon
                },
                messages: []
            }
            state.chatlist.unshift(session)
        }
        this.commit('GROUP_MEMBERS', { target: uid, pullMsg:pullMsg, head: 0 }) //获取群成员
    },
    // 群type处理
    GROUP_CHAT_TYPE(state, data){ 
        var _this = this
        var contentList = data.pullMsg.messageList
        contentList.map(item => {
            var msgType = _messageRes(item).content.type
            var msgContent = _messageRes(item).content.content
            if((_messageRes(item).content.data != "" && _messageRes(item).content.data) && (msgType == 1 || msgType == 105 || msgType == 106 || msgType == 108 || msgType == 110 ||  msgType == 104)){
                var groupData =  _messageRes(item).content.data ? JSON.parse(byteToString(_messageRes(item).content.data)) : ''
            }

            console.log(data.pullMsg)
            var redDot = () => {
                if(data.pullMsg.ident == 1){
                    return 1
                }else{
                    if(state.selectId == data.uid) return 1
                    else return 0
                }
            }
            switch(msgType){
                case 1: //正常发送文本消息
                    var from_user_type4 = data.session.members.find(item => item.type == 4)
                    if(from_user_type4){
                        if(from_user_type4.type != 4){
                            this.commit('GROUP_MSG',{session:data.session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                        }
                    }else{
                        this.commit('GROUP_MSG',{session:data.session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                    }
                    break
                case 105: //群加人 105
                    var addPerson = [_userRequest(groupData.o)]
                    groupData.ms.map(item => addPerson.push(_userRequest(item)))
                    mqtt.mqttPublish('UPUI', _pullUserRequest(addPerson), (res) => {
                        let userInfo = _userResult(res)
                        let names = ''
                        var qz = ''
                        userInfo.map((item, index) => {
                            if (item.uid == groupData.o) {
                                qz = item
                            }
                            if (groupData.o != item.uid) {
                                names += userInfo.length - 1 == index ? item.displayName : item.displayName + ", "
                            }
                            if (groupData.o == state.user.userId) {
                                msgContent = "你邀请了 " + names + " 加入群聊"
                            } else {
                                if (item.uid == state.user.userId) {
                                    msgContent = qz.displayName + " 邀请 你 加入群聊"
                                } else {
                                    msgContent = qz.displayName + " 邀请 " + names + " 加入群聊"
                                }
                            }
                        })
                        this.commit('GROUP_MSG',{session:data.session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                    })
                    break
                case 106: //群踢人 106
                    var removePerson =  [_userRequest(groupData.o)]
                    groupData.ms.map(item => removePerson.push(_userRequest(item)))
                    mqtt.mqttPublish('UPUI', _pullUserRequest(removePerson), (res) => {
                        let userInfo = _userResult(res)
                        let names = ''
                        var qz = ''
                        userInfo.map((item, index) => {
                            if (item.uid == groupData.o) {
                                qz = item
                            }
                            if (groupData.o != item.uid) {
                                names += userInfo.length - 1 == index ? item.displayName : item.displayName + ", "
                            }
                            if (groupData.o == state.user.userId) {
                                msgContent = "你把 " + names + " 移出群聊"
                            } else {
                                if (item.uid == state.user.userId) {
                                    msgContent = qz.displayName + " 把你移出群聊"
                                } else {
                                    msgContent = qz.displayName + " 把 " + names + " 移出群聊"
                                }
                            }
                        })
                        this.commit('GROUP_MSG',{session:data.session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                    })
                    break
                case 108:
                    // type = 108 解散群聊
                    if(_messageRes(item).from_user == state.user.userId){
                        state.chatlist.splice(state.chatlist.find(item => item.uid == data.uid), 1)
                        state.selectId = 0
                    }else{
                        msgContent = "该群已被解散"
                        var session = state.chatlist.find(item => item.uid == data.uid)
                        this.commit('GROUP_MSG',{session:session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                    }
                    break
                default:
                    if(data.pullMsg.ident == 0){
                        if( _messageRes(item).from_user == state.user.userId && msgType == 104)state.selectId = data.uid
                    }
                    
                    // type = 104  创建群
                    if(msgType == 104){
                        if (groupData.o == state.user.userId) {
                            msgContent = "你邀请了" + groupData.n + "加入群聊"
                        } else {
                            let info = state.friendlist.find(item => item.uid == groupData.o)
                            msgContent = info.displayName + " 邀请了 " + groupData.n + " 加入群聊"
                        }
                    }
                    // type = 110 修改群名称
                    if(msgType == 110){
                        if (groupData.o == state.user.userId) {
                            msgContent = "你修改群名为 " + groupData.n
                        } else {
                            let info = state.friendlist.find(item => item.uid == groupData.o)
                            msgContent = info.displayName + " 修改群名为 " + groupData.n
                        }
                        data.session.user.name = groupData.n
                    }

                    if(msgType == 104 || msgType == 110 || msgType == 3){

                        this.commit('GROUP_MSG',{session:data.session,msg:_messageRes(item),redDot:redDot(),msgContent:msgContent})
                    }
            }
            
        })
    },
    // 群msg
    GROUP_MSG(state,data){
        data.session.messages.push({
            user: {
                name: data.session.memberListInfo[data.msg.from_user].displayName,
                portrait: data.session.memberListInfo[data.msg.from_user].portrait
            },
            type: data.msg.content.type,
            content: data.msgContent,
            data: arrayBufferToBase64(data.msg.content.data),
            remoteMediaUrl: data.msg.content.remoteMediaUrl,
            date: data.msg.server_timestamp,
            redDot: data.redDot, //判断是否读取过   0未读取过 1读取过
            self: data.msg.from_user == state.user.userId ? true : false
        })
    },
    // 接收消息
    RECEIVE_MSG(state, msgs) {
        if (msgs.topic === 'MN') {
            let mn = _notifyMessage(msgs.msg)
            let parm = {
                id: Long.fromString(state.msg_head),
                //    id: '1564992702798',
                type: mn.type
            }
            mqtt.mqttPublish('MP', _pullMessageRequest(parm), (data) => {
                var pullMsg = _pullMessageResult(data)
                var type = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.type //单聊 0 群聊 2
                state.msg_head = pullMsg.head  // 改变全局head，用来记录每次发消息的时间
                pullMsg.ident = 0 //判断是即时还是历史记录列表拉取
                if (type == 0) { //私聊
                    this.commit('PRIVATE_CHAT', pullMsg)
                } else { //type = 1 群聊
                    // var uid = _messageRes(pullMsg.messageList[pullMsg.messageList.length - 1]).conversation.target
                    // this.commit('GROUP_CHAT', pullMsg)
                    this.commit('CHAT_GROUP_TYPE', pullMsg) //获取群信息
                }
            })
        }
    },
    //获取历史消息
    get_History(state) {
        let _this = this
        let parm = {
            id: 0,
            type: 0
        }
        mqtt.mqttPublish('MP', _pullMessageRequest(parm), (data) => {
            var pullMsg = _pullMessageResult(data)
            let hash = {}
            const newResult = pullMsg.messageList.reduceRight((item, next) => {
                hash[_messageRes(next).conversation.target] ? '' : hash[_messageRes(next).conversation.target] = true && item.push(next);
                return item
            }, []);
            newResult.map((item, index) => {
                // 私聊
                if (_messageRes(item).conversation.type == 0) {
                    let contentList = []
                    pullMsg.messageList.map(content =>{
                        if(_messageRes(content).conversation.type == 0){
                            if((_messageRes(item).conversation.target == _messageRes(content).conversation.target&&_messageRes(item).from_user == _messageRes(content).from_user)||
                            _messageRes(item).conversation.target == _messageRes(content).conversation.target&&_messageRes(item).from_user == _messageRes(item).conversation.target){
                                contentList.push(content)
                            }
                        }
                    })
                    _this.commit('PRIVATE_CHAT', {messageList:contentList,ident:1})  // 1 表示历史记录调用  2 正常群聊
                } 
                // 群聊
                else {
                    let contentList = []
                    pullMsg.messageList.map(content =>{
                        if(_messageRes(content).conversation.type == 1){
                            if(_messageRes(item).conversation.target == _messageRes(content).conversation.target){
                                contentList.push(content)
                            }
                        }
                    })
                    this.commit('CHAT_GROUP_TYPE', {messageList:contentList,ident:1}) //获取群信息
                }
            })
        })
    },
    // 选择好友后，点击发送信息。判断在聊天列表中是否有该好友，有的话跳到该好友对话。没有的话
    // 添加该好友的对话 并置顶
    send(state) {
        let result = state.friendlist.find(friend => friend.uid === state.selectFriendId)
        let session = state.chatlist.find((item, i) => {
            if (item.uid == result.uid) {
                let obj = state.chatlist.splice(i, 1)
                state.chatlist.unshift(obj[0])
            }
            return item.uid == result.uid
        })
        if (!session) {
            state.selectId = result.uid
                // for (let i = 0; i < state.chatlist.length; i++) {
                //     state.chatlist[i].id++;
                //     state.chatlist[i].index++;
                // }
            state.chatlist.unshift({
                uid: result.uid,
                type: result.type,
                user: {
                    name: result.displayName,
                    portrait: result.portrait
                },
                messages: [],
                index: 1
            })
            router.push({ path: '/chat' })
        } else {
            state.selectId = result.uid
            router.push({ path: '/chat' })
        }
    },
    //
    CLOSE(state) {
        state.user = {
                name: '',
                portrait: '',
                userId: '',
                msg_head: ''
            }
            // 对话好友列表
        state.chatlist = []
            // 好友列表
        state.friendlist = []
            // 群列表：
        state.grouplist = [],
            // 得知当前选择的是哪个对话
            state.selectId = 0,
            // 得知当前选择的是哪个好友
            state.selectFriendId = 0,
            // url 群合成图片用
            sessionStorage.clear()
            //断开
        mqtt.mqttDisconnect()
        router.push({ path: '/login' })
    },
    //添加群成员
    add_member(state, list) {
        let arr = [];
        list.list.map(item => arr.push(_groupMember(item.uid)))
        var parm = {
            uid: list.uid,
            list: arr
        }

        mqtt.mqttPublish('GAM', _AddGroupMemberRequest(parm), (data) => {})
    },
    //删除群成员
    remove_member(state, list) {
        let arr = [];
        list.list.map(item => arr.push(item.uid))
        var parm = {
            uid: list.uid,
            list: arr
        }
        mqtt.mqttPublish('GKM', _RemoveGroupMemberRequest(parm), (data) => {})
    }
    //
}
const getters = {
    // 筛选出含有搜索值的聊天列表
    searchedChatlist(state) {
        let sessions = state.chatlist.filter(sessions => sessions.user.name.includes(state.searchText));
        sessions.sort(function(a, b) {
            var x = a.date
            var y = b.date
            return x > y ? -1 : x < y ? 1 : 0;
        });
        return sessions
    },
    // 筛选出含有搜索值的好友列表
    searchedFriendlist(state) {
        let friends = state.friendlist.filter(friends => friends.alias ? friends.alias.includes(state.searchText) : friends.displayName.includes(state.searchText));
        return friends
    },
    // 通过当前选择是哪个对话匹配相应的对话
    selectedChat(state) {
        let session = state.chatlist.find(session => session.uid === state.selectId);
        // session.messages.map(item => {
        //     if(item.remoteMediaUrl){
        //         session.
        //     }
        //     console.log(item)
        // })
        return session
    },
    // 通过当前选择是哪个好友匹配相应的好友
    selectedFriend(state) {
        let friend = state.friendlist.find(friend => friend.uid === state.selectFriendId);
        console.log(friend)
        return friend
    },
    messages(state) {
        let session = state.chatlist.find(session => session.uid === state.selectId);
        return session.messages
    }
}

const actions = {
    search: ({ commit }, value) => {
        setTimeout(() => {
            commit('search', value)
        }, 100)
    },
    selectSession: ({ commit }, value) => commit('selectSession', value),
    selectFriend: ({ commit }, value) => commit('selectFriend', value),
    sendMessage: ({ commit }, msg) => commit('sendMessage', msg),
    send: ({ commit }) => commit('send'),
    initData: ({ commit }) => commit('initData'),
    // 获取好友
    FRIEND_LIST: ({ commit }) => commit('FRIEND_LIST'),
    // 创建群
    CREATING_GROUP: ({ commit }, list) => commit('CREATING_GROUP', list),
    // 退出
    CLOSE: ({ commit }) => commit('CLOSE'),
    // 消息列表历史消息
    get_History: ({ commit }, list) => commit('get_History', list),
    // 添加群成员
    add_member: ({ commit }, list) => commit('add_member', list),
    // 删除群成员
    remove_member: ({ commit }, list) => commit('remove_member', list),
    // 发送图片和发送图片上传图片成功并发送
    sendPhoto: ({ commit }, msg) => commit('sendPhoto', msg),
    handlePhotoRes: ({ commit }, msg) => commit('handlePhotoRes', msg),
}


// // 监听聊天列表的值， 发生变化就保存在localStorage中
// store.watch(
//     (state) => state.chatlist,
//     (val) => {
//         localStorage.setItem('vue-chat', JSON.stringify(val));
//     }, {
//         deep: true
//     }
// )


export default {
    state,
    mutations,
    getters,
    actions
}